package cc.lzmsh.service.impl;

import cc.lzmsh.config.OSSConfig;
import cc.lzmsh.domain.result.Result;
import cc.lzmsh.enums.AppHttpCodeEnum;
import cc.lzmsh.exception.SystemException;
import cc.lzmsh.service.UploadService;
import com.aliyun.oss.OSS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * Author:   msh
 * Date:     2024/9/23 下午2:14
 * Description:
 */

@Service("uploadService")
public class UploadServiceImpl implements UploadService {
    private final OSS ossClient;
    private final String bucketName;

    @Autowired
    public UploadServiceImpl(OSS ossClient, OSSConfig ossConfig) {
        this.ossClient = ossClient;
        this.bucketName = ossConfig.getBucketName();
    }

    @Override
    public Result uploadImg(MultipartFile file) throws SystemException {
        String filename = file.getOriginalFilename();
        if (filename != null && !filename.toLowerCase().endsWith(".png")) {
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        // 获取当前日期
        LocalDate date = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
        String datePath = date.format(formatter);

        // 使用uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // 获取扩展名
        String filenameExtension = StringUtils.getFilenameExtension(filename);
        // 拼接文件名
        String fileName = datePath + "/" + uuid + "." + filenameExtension;
        try {
            // todo 使用redis限制上传次数
            // 上传文件
            ossClient.putObject(bucketName, fileName, file.getInputStream());
            fileName = "https://msh-blog.oss-cn-guangzhou.aliyuncs.com" + "/" + fileName;
            return Result.success(fileName);
        } catch (Exception e) {
            throw new SystemException(AppHttpCodeEnum.FILE_ERROR);
        }
    }
}
